﻿
Imports AutoMapper
Imports CookComputing.XmlRpc
Imports FTTK.Exceptions

Namespace Services.Implementations.XmlRpc
    Friend NotInheritable Class BaseServiceMapping
        Private Sub New()

        End Sub

        ''' <summary>
        ''' Defines the mapping for Automapper.
        ''' </summary>
        ''' <remarks></remarks>
        Friend Shared Sub DefineMapping()

            Mapper.CreateMap(Of XmlRpcFaultException, FotoliaException)() _
                .ForMember(Function(a) a.Code, Sub(x) x.MapFrom(Function(a) a.FaultCode.ToString())) _
                .ForMember(Function(a) a.Message, Sub(x) x.MapFrom(Function(a) a.FaultString)) _
                .ForMember(Function(a) a.InnerException, Sub(x) x.MapFrom(Function(a) a))

            Mapper.CreateMap(Of XmlRpcStruct, Entities.FotoliaData)() _
                .ForMember(Function(a) a.NumberOfMedia, Sub(x) x.MapFrom(Function(a) If(a.ContainsKey("nb_media"), CInt(a.Item("nb_media")), -1))) _
                .ForMember(Function(a) a.Languages, Sub(x) x.ResolveUsing(Function(a)
                                                                              If a.ContainsKey("languages") Then
                                                                                  Dim list = New List(Of Entities.Language)
                                                                                  Dim languages = CType(a.Item("languages"), XmlRpcStruct)
                                                                                  For Each key In languages.Keys
                                                                                      list.Add(Mapper.Map(Of XmlRpcStruct, Entities.Language)(CType(languages.Item(key), XmlRpcStruct)))
                                                                                  Next
                                                                                  Return list
                                                                              Else
                                                                                  Return Nothing
                                                                              End If
                                                                          End Function))

            Mapper.CreateMap(Of XmlRpcStruct, Entities.Language)() _
                .ForMember(Function(a) a.Id, Sub(x) x.MapFrom(Function(a) CInt(a.Item("id")))) _
                .ForMember(Function(a) a.Name, Sub(x) x.MapFrom(Function(a) a.Item("name").ToString))

            Mapper.CreateMap(Of XmlRpcFaultException, [Error])() _
                .ForMember(Function(a) a.Code, Sub(x) x.MapFrom(Function(a) a.FaultCode.ToString())) _
                .ForMember(Function(a) a.Message, Sub(x) x.MapFrom(Function(a) a.FaultString))

        End Sub
    End Class
End Namespace